package com.hhq.cloud.controller;

import com.hhq.cloud.domain.pojo.PodInfo;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class PodController {

    @Resource
    private KubernetesClient kubernetesClient;

    /**
     * 获取pods信息
     * @param namespace
     * @return
     */
    @GetMapping("/pods")
    public List<PodInfo> listPods(@RequestParam("namespace") String namespace) {
        List<Pod> pods = kubernetesClient.pods().inNamespace(namespace).list().getItems();
        List<PodInfo> result = new ArrayList<>();

        for (Pod pod : pods) {
            List<String> containers = pod.getSpec().getContainers().stream()
                    .map(Container::getName)
                    .collect(Collectors.toList());

            result.add(new PodInfo(pod.getMetadata().getName(), containers));
        }
        return result;
    }
}
